package com.zimi.controller;

import com.zimi.model.SysUser;
import com.zimi.service.RegistryService;
import com.zimi.util.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Api("注册用户")
@Controller
@RequestMapping("registry")
public class RegistryApi {

    @Autowired
    private RegistryService registryService;


    @PostMapping("sendVerifiNumber")
    @ApiOperation("发送验证码")
    @ResponseBody
    public Object sendVerifiNumber(HttpServletRequest request, HttpServletResponse response) {

        String[] ma = request.getParameterValues("phone");
        registryService.sendVerification(ma[0]);

        Map map = new HashMap();
        map.put("code", 0);
        return map;
    }

    @PostMapping("retrySendVerifiNumber")
    @ApiOperation("重新发送验证码")
    @ResponseBody
    public Object retrySendVerifiNumber() {
        // 1)取出验证码
        Session session = ShiroUtils.getSession();
        Object obj = session.getAttribute("phone");

        if (obj == null) {
            throw new RuntimeException("确认验证码失败，请重新取得验证码。");
        }

        registryService.sendVerification((String) obj);

        Map map = new HashMap();
        map.put("code", 0);
        return map;
    }

    @PostMapping("verification")
    @ApiOperation("确认验证码")
    @ResponseBody
    public Object verification(HttpServletRequest request, HttpServletResponse response) {

        String[] ma = request.getParameterValues("verifyCode");
        registryService.verify(ma[0]);

        Map map = new HashMap();
        map.put("code", 0);
        return map;
    }

    @GetMapping("page1")
    public String reg() {
        return "registryPage1";
    }

    @GetMapping("page2")
    public String regNext() {
        // 1)取出验证码
        Session session = ShiroUtils.getSession();
        Object obj = session.getAttribute("phoneCheck");

        if (obj == null) {
            return reg();
        } else {
            session.removeAttribute("phoneCheck");
            return "registryPage2";
        }
    }

    @PostMapping("registry")
    @ApiOperation("注册新用户")
    @ResponseBody
    public Object registry(SysUser sysUser) {
        registryService.registry(sysUser);

        Map map = new HashMap();
        map.put("code", 0);
        return map;
    }
}
